//
//  SHPRefresh.swift
//  weibo
//
//  Created by songhuipan on 16/4/24.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit
// MARK:刷新控件的状态
enum refreshState:Int {
    /// 正常状态
    case Normal = 0
    /// 下拉
    case pulling = 1
    /// 刷新中
    case refreshing = 2
}
/// 刷新控件的高度
private let refreshHeight:CGFloat = 50

class SHPRefresh: UIControl {
    // MARK:控件的刷新状态
    var UIState:refreshState = refreshState.Normal {
        didSet{
            
            switch UIState {
             case .Normal:
                messageLabel.text = "正常状态"
                if oldValue == .refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= refreshHeight
                    })
                }
            case .pulling:
                messageLabel.text = "松手刷新"
            case .refreshing:
                messageLabel.text = "刷新中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += refreshHeight
                    }, completion: { (_) -> Void in
                        // 通知外界开始刷新了
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
                
            }
        }
    }
/// 停止刷新的方法
    func endRefreshing(){
        UIState = .Normal
    }
    /// 刷新控件添加到的父控件
    var scrollView:UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK:KVO监测方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 刷新的临界值
        let contentOffsetMargin = -(refreshHeight + (scrollView?.contentInset.top)!)
//        let contentOffsetMargin = CGFloat(-114)
        // UI控件的偏移
        let contentOffsetY = scrollView?.contentOffset.y
        // 父控件在滑动
        if scrollView!.dragging {
            // 避免滑动没有达到临界值时，一直执行状态的setter方法
            if contentOffsetMargin < contentOffsetY && UIState == .pulling {
                UIState = .Normal
            }else if contentOffsetMargin >= contentOffsetY{
                UIState = .pulling
            }
        }else {
            // 没有滑动，并且控件的状态为下拉时，刷新
            if contentOffsetMargin >= contentOffsetY && UIState == .pulling{
                UIState = .refreshing
            }
        }
        
    }
    // MARK:重写父类UIView的方法，监听刷新控件添加到谁身上
    override func willMoveToSuperview(newSuperview: UIView?) {
        if let scrollView = newSuperview as? UIScrollView {
            // 赋值给属性控件
            self.scrollView = scrollView
            // 添加KVO监听其属性contentOffset的变化
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    // MARK:设置刷新控件及其子控件的frame值
    override func layoutSubviews() {
        self.frame = CGRectMake(0, -refreshHeight, kScreenWidth, refreshHeight)
        messageLabel.frame = CGRectMake(0, 0, kScreenWidth, refreshHeight)
    }
    
    // MARK:懒加载刷新控件中显示文字的部分
    private lazy var messageLabel:UILabel = {
        let lab = UILabel(textColor: UIColor.whiteColor(), textFont: 14)
        lab.textAlignment = .Center
        lab.text = "正常状态"
        return lab
        
    }()
    // MARK:移除观察者
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
extension SHPRefresh {
    // MARK:设置刷新控件UI
    func setupUI (){
        self.backgroundColor = getColorWithRGB(55, green: 105, blue: 65)
        addSubview(messageLabel)
    }
}














